// React基础组件
import React from 'react'
// dva 连接组件 - 连接route和model
import { connect } from 'dva'
// 引入antd的组件
import { Form,Radio, Button,Popconfirm, Modal, Row, Col, Input, Select, Cascader, Icon, Checkbox, Tabs, DatePicker, message } from 'antd'
//导入路由组件，用于跳转等
import { Link, hashHistory } from 'dva/router'
// 导入项目全局配置文件
import config from 'config/config'
// 引入model取值工具方法
import { mapStateToProps } from 'utils/view_utils'
// 当前组件样式
import styles from './soilFilmMarketDetailStyle.less'
import { CollapsiblePanels } from 'widget/CollapsiblePanels/index'
import { Grid } from 'widget/Grid/index'
import moment from 'moment';
import Track from 'widget/Map/TrackB'

const FormItem = Form.Item
const { RangePicker } = DatePicker
const { Option } = Select;
const { TextArea } = Input;
const InputGroup = Input.Group;
/**
 * description 路由视图及事件处理
 * dispatch 分发到models中的effects对应事件名
 * model 用于获取models中state定义的数据
 * form 表单对象
 */
const soilFilmMarketDetailView = function ({ dispatch, model, form }) {
  // 表单的子函数
  const { resetFields, getFieldDecorator, validateFields, setFieldsValue,validateFieldsAndScroll  } = form
  // 取出model对象，命名空间
  const { modelObj, namespace } = model
  let {newProduct,brandModal,paramsObj,tempId,attributeList,Mapmodel,cityList,query, actionType, btnLoading,loading } = modelObj

  const formItemLayoutPro = {
    labelCol: { span: 6 },
    wrapperCol: { span: 14 },
  };
  const formItemLayoutPro1 = {
    labelCol: { span: 4 },
    wrapperCol: { span: 20 },
  };
 //地图
 const mapQueryList = [
    { name: '省市', type: 'cascader', list: cityList, key: 'code', value: '' },
    { name: '分销商名称', type: 'text', key: 'sellerName', value: '' }
  ];
// 城市
function selectCity(val,id) {
  for(var item of attributeList){
    if(item.id == id){
      item.defaultValue = val
    }
  }
  dispatch({
      type: `${namespace}/updateStore`,
      payload: { attributeList }
  })
}
//输入框改变时
function inputChange(value,id) {
  for(var item of attributeList){
    if(item.id == id){
      item.defaultValue = value
    }
  }
  dispatch({
    type: `${namespace}/updateStore`,
    payload: {attributeList}
  })
  let firstHousePrice =  attributeList.filter(item => item.tableField=='firstHousePrice')[0].defaultValue
  let realHousePrice =  attributeList.filter(item => item.tableField=='realHousePrice')[0].defaultValue
  for(var item of attributeList){
    if(item.tableField == 'premiumRates'&&realHousePrice&&firstHousePrice){
      item.defaultValue = Math.round((parseFloat(realHousePrice)-parseFloat(firstHousePrice))/parseFloat(firstHousePrice)*100)
    }
  }
  dispatch({
    type: `${namespace}/updateStore`,
    payload: {attributeList}
  })
}
function inputGroupChange(value, name,id) {
  if(name=='houseTypeName_0'){
    paramsObj.houseTypeName[0] = value
  }
  if(name=='houseTypeName_1'){
    paramsObj.houseTypeName[1] = value
  }
  for(var item of attributeList){
    if(item.id == id){
      item.defaultValue = paramsObj.houseTypeName
    }
  }
  dispatch({
    type: `${namespace}/updateStore`,
    payload: {attributeList,paramsObj}
  })
}

  // 多选改变
  function multipleChange (value,id) {
    for(var item of attributeList){
      if(item.id == id){
        item.defaultValue = value.join(',')
      }
    }
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {attributeList}
    })
  }


  function updateMapmodel(status,id) {
    if(id){
      tempId = id
      dispatch({
        type: `${namespace}/updateStore`,
        payload: {tempId }
      });
    }
    dispatch({
      type: `${namespace}/updateStore`,
      payload: { Mapmodel: status}
    });
  }
  //弹出框回调
  function cbk( latAndLon,mapAddress) {
    for(var item of attributeList){
      if(item.id == tempId){
        item.defaultValue = mapAddress
      }
    }
    paramsObj.latAndLon = latAndLon
    dispatch({
      type: `${namespace}/updateStore`,
      payload: { paramsObj,attributeList }
    });
    form.resetFields('tempId')
  }

  //新增竞品品牌
  function updateCancel(){
    brandModal.visible = !brandModal.visible
    form.resetFields()
    dispatch({
      type: `${namespace}/updateStore`,
      payload: { brandModal}
    })
  }
  function onSubmit(){
    if(!newProduct){
      message.warning('请先添加竞品')
      return
    }
    let list = attributeList.filter(item=>item.tableField=='brand')[0].itemContent.split(",")
    list.push(newProduct)
    for(var item of attributeList){
      if(item.tableField == 'brand'){
        item.itemContent = list.join(',')
        dispatch({
          type: `${namespace}/addlittle`,
          payload: { id: item.id,itemContent:item.itemContent}
        })
      }
    }
    dispatch({
      type: `${namespace}/updateStore`,
      payload: { attributeList}
    })
    updateCancel()
  }

  function inputZituoChange(value,name){
    newProduct = value
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {newProduct}
    })
  }

  function submit(){
    validateFieldsAndScroll((err) => {
      if (err) {
        return false
      } else {
        dispatch({
          type: `${namespace}/submit`,
          payload: {}
        })
      }
    })
  }
  return (
    <div className='public_listMain'>
      <div className={"functionButton"}>
        <Button disabled={actionType == 'check'} type='primary' onClick={e => submit()} loading={btnLoading}>提交</Button>
      </div>

      <CollapsiblePanels title="土拍市场详情" hideUpDownBtn={true} >
        {attributeList == undefined ?null:attributeList.map((item)=>{
            if(item.isRadio=='1'){ //单选
              return  (<Row key={item.id}>
                          <Col span={16}>
                              <FormItem label={item.attributeName}  {...formItemLayoutPro}>
                              {getFieldDecorator(item.id, {
                                  rules: [{
                                  required: item.isShow=='1'?true:false, message: '请选择'+item.attributeName
                                  }],
                                  initialValue: item.defaultValue
                              })(
                                  <Select disabled={actionType == 'check'} placeholder={'请选择'+item.attributeName} onChange={(e) => { inputChange(e, item.id) }}>
                                      {item.itemContent.split(",").map((itemd)=>{
                                        return <Select.Option key={itemd} value={itemd}>{itemd}</Select.Option>
                                      })}
                                  </Select>
                              )}
                              </FormItem>
                          </Col>
                      </Row>)
            }else if(item.isRadio=='2'){ //多选
              return  (<Row key={item.id}>
                  <div style={{marginLeft:'16.6%',color:'red',}}>注：若在竞得单位无法查找所需品牌，请点击添加</div>
                  <Col span={16}  style={{position: 'relative'}}>
                      <FormItem label={item.attributeName}  {...formItemLayoutPro}>
                      {getFieldDecorator(item.id, {
                          rules: [{
                          required: item.isShow=='1'?true:false, message: '请选择'+item.attributeName
                          }],
                          initialValue: item.defaultValue?item.defaultValue.split(","):[]
                      })(
                        <Select
                        mode="multiple"
                        optionFilterProp="children"
                        filterOption={true}
                        placeholder={"请选择"+item.attributeName}
                        onChange={(e, v) => {       
                          let arr = []
                          v.map((itt) => {
                            arr.push(itt.props.value)
                          })
                          multipleChange(arr, item.id)
                        }}
                        style={{ width: '100%' }}
                      >
                        {item.itemContent.split(",").map((itemd, idx) => {
                          return (
                            itemd?
                            <Option key={idx+''} value={itemd}>{itemd}</Option>:null
                          )
                        })}
                      </Select>
                      )}
                      </FormItem>
                      <Button  style={{position: "absolute",right:'16.8%',top: '4px', cursor: "pointer",zIndex: 99}} type='primary' onClick={() => { updateCancel() }}>添加</Button>
                  </Col>
              </Row>)
            }else if(item.isRadio=='3'){//文本
            if(item.tableField == 'premiumRates'){
                return  (<Row key={item.id}>
                  <Col span={16}> 
                      <FormItem label={item.attributeName}  {...formItemLayoutPro}>
                      {getFieldDecorator(item.id, {
                          rules: [{
                          required: item.isShow=='1'?true:false, message: '请输入'+item.attributeName
                          },{ pattern: /^[+-]?\d*\.?\d*$/, message: '请输入数字' }],
                          initialValue:  item.defaultValue +''
                      })(
                        <Input disabled={true} placeholder={'请输入'+item.attributeName} id='premiumRates' onChange={(e) => { inputChange(e.target.value, item.id) }} />
                      )}
                      </FormItem>
                  </Col>
                </Row>)
              }else if(item.tableField == 'firstHousePrice'||item.tableField == 'realHousePrice'){
                return  (<Row key={item.id}>
                  <Col span={16}> 
                      <FormItem label={item.attributeName}  {...formItemLayoutPro}>
                      {getFieldDecorator(item.id, {
                          rules: [{
                          required: item.isShow=='1'?true:false, message: '请输入'+item.attributeName
                          },{ pattern: /^[+-]?\d*\.?\d*$/, message: '请输入数字' }],
                          initialValue:  item.defaultValue +''
                      })(
                        <Input disabled={actionType == 'check'} placeholder={'请输入'+item.attributeName} id='premiumRates'  onChange={(e) => { inputChange(e.target.value, item.id) }} />
                      )}
                      </FormItem>
                  </Col>
                </Row>)
              }else if(item.tableField == 'landName'){
                return  (<Row key={item.id}>
                  <Col span={16}> 
                      <FormItem label={item.attributeName}  {...formItemLayoutPro}>
                      {getFieldDecorator(item.id, {
                          rules: [{
                          required: item.isShow=='1'?true:false, message: '请输入'+item.attributeName
                          }],
                          initialValue:  item.defaultValue +''
                      })(
                        <Input disabled={actionType == 'check'} placeholder={'请输入'+item.attributeName}   onChange={(e) => { inputChange(e.target.value, item.id) }} />
                      )}
                      </FormItem>
                  </Col>
                </Row>)
              }else{
                return  (<Row key={item.id}>
                  <Col span={16}> 
                      <FormItem label={item.attributeName}  {...formItemLayoutPro}>
                      {getFieldDecorator(item.id, {
                          rules: [{
                          required: item.isShow=='1'?true:false, message: '请输入'+item.attributeName
                          },{ pattern: /^[+-]?\d*\.?\d*$/, message: '请输入数字' }],
                          initialValue:  item.defaultValue +''
                      })(
                        <Input disabled={actionType == 'check'} placeholder={'请输入'+item.attributeName}   onChange={(e) => { inputChange(e.target.value, item.id) }} />
                      )}
                      </FormItem>
                  </Col>
                </Row>)
              }
            }else if(item.isRadio=='4'){//s框
              return  (<Row key={item.id}>
                <Col span={16}> 
                  <FormItem label={item.attributeName}  {...formItemLayoutPro} style={{display: 'flex'}}>
                    {getFieldDecorator('houseTypeName', {
                      initialValue: item.defaultValue,
                      rules: [
                        { required: true,  message: '请输入',type: 'array' },
                        { validator: (rule, value, callback) => {
                            ((value || value + '' === '0') && ('' + value).search(/^(0|[1-9]\d{0,9})$/)) ? callback('限制为10位以内的整数') : callback();
                          } },
                      ],
                    })(
                      <InputGroup compact >
                        <Input
                          style={{width:'33.3%',verticalAlign: 'middle'}}
                          addonAfter="~"
                          value={item.defaultValue[0]}
                          onChange={(e) => { inputGroupChange(e.target.value.replace(/[^\-?\d.]/g,''), 'houseTypeName_0',item.id) }}
                        />
                        <Input
                          style={{width:'33.3%',verticalAlign: 'middle'}}
                          value={item.defaultValue[1]}
                          onChange={(e) => { inputGroupChange(e.target.value.replace(/[^\-?\d.]/g,''), 'houseTypeName_1',item.id) }}
                        />
                      </InputGroup>
                    )}
                  </FormItem>
                </Col>
            </Row>)
          }else if(item.isRadio=='5'){ //日期
              return  (<Row key={item.id}>
                <Col span={16}>
                    <FormItem label={item.attributeName}  {...formItemLayoutPro}>
                    {getFieldDecorator(item.id, {
                        rules: [{
                        required: item.isShow=='1'?true:false, message: '请选择'+item.attributeName
                        }],
                        initialValue:  item.defaultValue ? moment(item.defaultValue, 'YYYY-MM-DD') : null
                    })(
                      <DatePicker disabled={actionType == 'check'} format="YYYY-MM-DD" onChange={(e,val) => {inputChange(val, item.id)}} />
                    )}
                    </FormItem>
                </Col>
            </Row>)
            }else if(item.isRadio=='6'){ //富文本
              return  (<Row key={item.id}>
                <Col span={16}>
                    <FormItem label={item.attributeName}  {...formItemLayoutPro}>
                    {getFieldDecorator(item.id, {
                        rules: [{
                        required: item.isShow=='1'?true:false, message: '请输入'+item.attributeName
                        }],
                        initialValue:  item.defaultValue
                    })(
                      <TextArea maxLength={500} placeholder='请输入' rows={4} onChange={(e) => { inputChange(e.target.value, item.id) }}/>
                    )}
                    </FormItem>
                </Col>
            </Row>)
            }else if(item.isRadio=='10'){ //地址
              return  (<Row key={item.id}>
                <Col span={24}>
                  <FormItem {...formItemLayoutPro1}
                    label={item.attributeName}>
                    {getFieldDecorator(item.id, {
                      rules: [
                        {
                          required: true,
                          validator: (rule, value, callback) => {
                            if (!item.defaultValue||item.defaultValue=="") {
                              callback('请添加'+ item.attributeName)
                            } else {
                              callback()
                            }
                          }
                        },
                      ],
                    })(<Row style={{ border: 0 }}>
                    {actionType !== 'check'&& <Col span={2}><a onClick={(e) => { updateMapmodel(true,item.id) }}>选择</a></Col>}
                      <Col span={10}><span>{item.defaultValue}</span></Col>
                      {paramsObj.latAndLon && paramsObj.latAndLon.length > 0 ? <Col>
                        <Col span={5}><span>经度:{paramsObj.latAndLon[0]}</span>
                        </Col><Col span={5}>纬度:{paramsObj.latAndLon[1]}</Col>
                      </Col> : null}
                    </Row>)}
                </FormItem>
              </Col>
              </Row>)
            }else if(item.isRadio=='11'){ //城市
              return  (<Row key={item.id}>
                          <Col span={16}>
                              <FormItem label={item.attributeName}  {...formItemLayoutPro}>
                                {getFieldDecorator(item.id, {
                                    rules: [{
                                        required: true, message: '请选择'+item.attributeName
                                    }],
                                    initialValue: item.defaultValue||[]
                                })(
                                    <Cascader
                                        options={cityList}
                                        onChange={(val) => { selectCity(val, item.id) }}
                                        placeholder={'请选择'+item.attributeName}/>
                                )}
                            </FormItem>
                          </Col>
                      </Row>)
            }
          })}
      </CollapsiblePanels>
      <Track
        visible={Mapmodel}
        queryList={mapQueryList}
        btnDiv={true}
        latAndLon={paramsObj.latAndLon}
        cancal={e => updateMapmodel(false)}
        cbk={(v, b) => cbk(v, b)}
        options={cityList}
      />
      <Modal
          title="新增竞得单位"
          width='600px'
          visible={brandModal.visible}
          onOk={() => { onSubmit() }}
          onCancel={() => { updateCancel()}}
        >
          <Row>
            <Col span={24}>
              <FormItem label='竞得单位' extra={"注：若在竞得单位无法查找所需品牌，请在此新增"}  {...formItemLayoutPro}>
                {getFieldDecorator('brand', {
                  rules: [{
                    required: false, message: '请输入竞得单位'
                  }],
                  initialValue: query.brand
                })(
                  <Input placeholder='请输入竞得单位' onChange={(e) => { inputZituoChange(e.target.value, 'brand') }} />
                )}
              </FormItem>
            </Col>
          </Row>
        </Modal>
    </div>
  )
}

// 连接视图(view)和模型(model)
export default connect(mapStateToProps)(Form.create()(soilFilmMarketDetailView))